iT邦幫忙

2024 iThome 鐵人賽

DAY 4
0
佛心分享-刷題不只是刷題

刷題筆記系列 第 4

[Day4] Intersection of Two Arrays II

  • 分享至 

  • xImage
  •  

這一題其實以前就有寫過,只是當時還不知道Two Pointer的解題技巧,也是用迴圈粗暴解決,後來為了想要刻意練習使用Two Pointer技巧,又再重寫一次題目,結果第二次寫的時候反而一直卡在兩個非有序陣列要怎麼找到交集,卻沒有想到先使用排序,再使用Two Pointers,甚至還想到要把map搬出來用(啊不是就排序一下就解決了嗎?),反而第一次寫這題的時候,直覺解題第一念頭就想到要排序,有種越練越退步的感覺...

廢話不多說,開始解題吧!


Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

給定兩組整數陣列 nums1 和 nums2,返回它們的交集。回傳結果中每個元素的出現的次數應與它在兩個陣列中出現的次數相同,並且可以以任意順序回傳結果陣列。

範例如下
https://ithelp.ithome.com.tw/upload/images/20240816/20168667yFJktsuK0d.png


先拆解題目

  1. 先排序兩組陣列,由小至大排序

  2. 使用兩個指針pointer1、pointer2,兩者都從陣列0的位置開始跑

  3. 使用while迴圈迭代,while執行條件為兩個指針都不能大於各自原本陣列(nums1、nums2)的長度

  4. 迴圈內使用邏輯判斷
    4-1. 如果 nums1 在 pointer1 的整數 小於 nums2 在 pointer2 的整數
    pointer1往右移

    4-2. 如果 nums1 在 pointer1 的整數 大於 nums2 在 pointer2 的整數
    pointer2往右移

    4-3. 如果 nums1 在 pointer1 的整數 等於 nums2 在 pointer2 的整數
    → 將此數值放入要回傳結果的陣列ans裡面
    → pointer1、pointer2同時右移
    https://ithelp.ithome.com.tw/upload/images/20240816/201686679FX5Ypsf29.png

程式碼如下

var intersect = function(nums1, nums2) {
    // sort nums1 and nums2(sort in ascending order)
    nums1.sort((a, b) => a - b);
    nums2.sort((a, b) => a - b);
    //set pointers
    let pointer1 = 0;
    let pointer2 = 0;
    let ans = [];
    //use while loop to find intersection of two arrays, and two pointers must smaller than the length of array
    while (pointer1 < nums1.length && pointer2 < nums2.length) {
        if(nums1[pointer1] < nums2[pointer2]){
            pointer1++;
        } else if (nums1[pointer1] > nums2[pointer2]){
            pointer2++;
        } else {
            ans.push(nums1[pointer1]);
            pointer1++;
            pointer2++;
        }
    }
    return ans;
};

上一篇
[Day3]Remove Duplicates from Sorted Array
下一篇
[Day5]Fast and Slow Pointer & Floyd Cycle Detection Algorithm
系列文
刷題筆記20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言